package com.omniseckill.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.omniseckill.dto.Result;
import com.omniseckill.entity.ShopType;
import com.omniseckill.mapper.ShopTypeMapper;
import com.omniseckill.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.omniseckill.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 店铺类型查询
     *
     * @return
     */
    @Override
    public Result queryList() {
        //1.从redis中查询店铺类型的缓存
        String shopTypeJson = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_TYPE_KEY);
        //2.判断是否存在
        if (StrUtil.isNotBlank(shopTypeJson)){
            //3.存在，则直接返回——>将json转为字符串
            List<ShopType> shopTypeList = JSONUtil.toList(shopTypeJson, ShopType.class);
            return Result.ok(shopTypeList);
        }
        //4.不存在，查询数据库
        List<ShopType> shopTypes = query().orderByAsc("sort").list();
        //5.判断店铺类型是否存在,不存在，提示错误
        if (shopTypes == null){
            return Result.fail("店铺类型不存在！");
        }
        //6.存在，将店铺类型信息写入redis中
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_TYPE_KEY, JSONUtil.toJsonStr(shopTypes));

        return Result.ok(shopTypes);
    }
}
